package win.smartown.android.base

import android.os.Bundle
import android.support.annotation.IdRes
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.view.View
import rx.Observable
import rx.Subscriber
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subscriptions.CompositeSubscription
import win.smartown.android.request.RequestListener
import win.smartown.android.utils.SnackbarUtil

/**
 * Created by smartown on 2017/3/18 17:11.
 * Desc:
 */
open class SuperActivity : AppCompatActivity() {

    private var compositeSubscription: CompositeSubscription? = null
    private var snackbar: Snackbar? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        compositeSubscription = CompositeSubscription()
    }

    override fun onDestroy() {
        unSubscribe()
        super.onDestroy()
    }

    fun addSubscription(subscription: Subscription) {
        if (compositeSubscription == null) {
            compositeSubscription = CompositeSubscription()
        }
        compositeSubscription!!.add(subscription)
    }

    fun unSubscribe() {
        if (compositeSubscription != null) compositeSubscription!!.unsubscribe()
    }

    fun <T> request(observable: Observable<T>, listener: RequestListener<T>) {
        addSubscription(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(object : Subscriber<T>() {

            override fun onStart() {
                listener.onStart()
            }

            override fun onCompleted() {

            }

            override fun onError(e: Throwable) {
                listener.onFail(e)
            }

            override fun onNext(t: T) {
                listener.onSuccess(t)
            }
        }))
    }

    protected open fun <T : View> findView(@IdRes id: Int): T {
        return findViewById(id) as T
    }

    protected fun showSnackBar(text: CharSequence, action: CharSequence, actionListener: View.OnClickListener) {
        showSnackBar(text, 3000, action, actionListener)
    }

    @JvmOverloads protected fun showSnackBar(text: CharSequence, duration: Int = 3000, action: CharSequence? = null, actionListener: View.OnClickListener? = null) {
        if (snackbar == null) {
            snackbar = setupSnackbar()
        }
        snackbar!!.setText(text)
        snackbar!!.duration = duration
        if (!TextUtils.isEmpty(action) && null != actionListener) {
            snackbar!!.setAction(action, actionListener)
        }
        snackbar!!.show()
    }

    protected fun setupSnackbar(): Snackbar {
        return SnackbarUtil.newSnackbar(window.decorView)
    }

}
